package com.BoobooBot;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.skype.Chat;
import com.skype.ChatMessage;
import com.skype.Skype;
import com.skype.SkypeException;

public class CommandHandler {

	String regex = "([^\"]\\S*|\".+?\")\\s*";
	Chat chat;

	public CommandHandler() {
	}

	public String[] getArgs(ChatMessage c) throws SkypeException {
		List<String> matches = new ArrayList<String>();
		Matcher m = Pattern.compile(regex).matcher(c.getContent());

		while (m.find()) {
			// System.out.println(m.group(0).replace("\"", ""));
			matches.add(m.group(0).replace("\"", ""));
		}

		return matches.toArray(new String[0]);
	}

	public void executeCommand(ChatMessage c) throws SkypeException {

		Method m = null;
		try {
			m = this.getClass().getMethod(
					c.getContent().split(" ")[0].substring(1).toLowerCase(),
					new Class[] { String[].class });
			
		} catch (NoSuchMethodException | SecurityException | SkypeException e) {
			c.getChat().send("BoobooBot: Invalid Command");
			System.out.println(c.getChat().getId());
			return;
		}

		try {
			chat = c.getChat();
			m.invoke(this, new Object[] { getArgs(c) });
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
			chat.send("BoobooBot: Invalid Arguments");
		}
	}

	public void ping(String[] args) throws SkypeException,
			IllegalArgumentException {
		if (args.length != 2) {
			throw new IllegalArgumentException();
		}

		chat.send("BoobooBot: " + args[1]);
	}

	public void createchat(String[] args) throws SkypeException,
			IllegalArgumentException {

		if (args.length < 2) {
			throw new IllegalArgumentException();
		}
		
		for (int i = 0; i < args.length - 1; i++) {
			args[i] = args[i + 1].trim();
		}

		Chat chat = Skype.chat(args);
		chat.send("Welcome!");
	}
	
	public void call(String[] args) throws SkypeException {
		if (args.length < 2) {
			throw new IllegalArgumentException();
		}
		
		for (int i = 0; i < args.length - 1; i++) {
			args[i] = args[i + 1].trim();
		}

		Chat chat = Skype.chat(args);
		Skype.call(chat.getId());
	}
}